<template>
  <div class="login">
    <div class="login-container">
      <!-- 左侧 Logo 区域 -->
      <div class="logo-section">
        <div class="logo-wrapper">
          <div class="logo-animation">
            <img src="@/assets/images/logo.png" alt="XDOG Logo" class="main-logo">
          </div>
          <h1 class="logo-title">XDOG</h1>
          <p class="logo-subtitle">财富密码</p>
          <div class="logo-description">
            连接未来，共享价值
          </div>
        </div>
      </div>

      <!-- 右侧 登录表单区域 -->
      <div class="login-section">
        <div class="login-box">
          <div class="login-header">
            <h2>欢迎回来</h2>
          </div>

          <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
            <el-form-item prop="username">
              <el-input
                v-model="loginForm.username"
                size="large"
                type="text"
                auto-complete="off"
                :placeholder="proxy.$t('login.username')"
                class="custom-input"
              >
                <template #prefix>
                  <svg-icon icon-class="user" class="el-input__icon input-icon" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                v-model="loginForm.password"
                size="large"
                type="password"
                auto-complete="off"
                :placeholder="proxy.$t('login.password')"
                @keyup.enter="handleLogin"
                class="custom-input"
              >
                <template #prefix>
                  <svg-icon icon-class="password" class="el-input__icon input-icon" />
                </template>
              </el-input>
            </el-form-item>

            <el-form-item v-if="captchaEnabled" prop="code">
              <div class="captcha-container">
                <el-input
                  v-model="loginForm.code"
                  size="large"
                  auto-complete="off"
                  :placeholder="proxy.$t('login.code')"
                  class="custom-input captcha-input"
                >
                  <template #prefix>
                    <svg-icon icon-class="validCode" class="el-input__icon input-icon" />
                  </template>
                </el-input>
                <div class="login-code">
                  <img :src="codeUrl" class="login-code-img" @click="getCode" />
                </div>
              </div>
            </el-form-item>

            <div class="login-options">
              <el-checkbox v-model="loginForm.rememberMe" size="large">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
              <router-link v-if="register" to="/register" class="register-link">
                {{ proxy.$t('login.switchRegisterPage') }}
              </router-link>
            </div>

            <el-button
              :loading="loading"
              size="large"
              type="primary"
              style="width: 100%"
              @click.prevent="handleLogin"
              class="login-button"
            >
              <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
              <span v-else>{{ proxy.$t('login.logging') }}</span>
            </el-button>

            <div class="divider">
              <span>或使用以下方式登录</span>
            </div>

            <div class="social-login">
              <el-button size="large" circle :title="proxy.$t('login.social.wechat')" @click="doSocialLogin('wechat')">
                <svg-icon icon-class="wechat" />
              </el-button>
              <el-button size="large" circle :title="proxy.$t('login.social.maxkey')" @click="doSocialLogin('maxkey')">
                <svg-icon icon-class="maxkey" />
              </el-button>
              <el-button size="large" circle :title="proxy.$t('login.social.topiam')" @click="doSocialLogin('topiam')">
                <svg-icon icon-class="topiam" />
              </el-button>
              <el-button size="large" circle :title="proxy.$t('login.social.gitee')" @click="doSocialLogin('gitee')">
                <svg-icon icon-class="gitee" />
              </el-button>
              <el-button size="large" circle :title="proxy.$t('login.social.github')" @click="doSocialLogin('github')">
                <svg-icon icon-class="github" />
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!-- 底部 -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 疯狂的狮子Li All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const router = useRouter();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: '',
  password: '',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('login.rule.tenantId.required') }],
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(false);

// 注册开关
const register = ref(true);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = () => {
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        const redirectUrl = redirect.value || '/';
        await router.push(redirectUrl);
        loading.value = false;
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background: linear-gradient(135deg, #0f0c29, #302b63, #24243e);
  position: relative;
  overflow: hidden;

  &::before {
    content: "";
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, rgba(255,255,255,0) 70%);
    transform: rotate(30deg);
  }

  &::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    background:
      linear-gradient(90deg, transparent 50%, rgba(64, 158, 255, 0.05) 50%),
      linear-gradient(rgba(64, 158, 255, 0.05) 50%, transparent 50%);
    background-size: 50px 50px;
    opacity: 0.3;
  }

  .login-container {
    position: relative;
    z-index: 2;
    width: 100%;
    max-width: 1200px;
    height: calc(100vh - 100px); /* 改为动态高度 */
    min-height: 650px; /* 设置最小高度 */
    max-height: 800px; /* 设置最大高度 */
    display: flex;
    background: rgba(255, 255, 255, 0.08);
    backdrop-filter: blur(12px);
    border-radius: 24px;
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
    border: 1px solid rgba(255, 255, 255, 0.15);
    overflow: hidden;

    .logo-section {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background: linear-gradient(135deg, rgba(64, 158, 255, 0.15), rgba(26, 107, 237, 0.15));
      position: relative;
      overflow: hidden;

      &::before {
        content: "";
        position: absolute;
        top: -50%;
        left: -50%;
        width: 200%;
        height: 200%;
        background: conic-gradient(
          transparent,
          rgba(64, 158, 255, 0.4),
          transparent 30%
        );
        animation: rotate 8s linear infinite;
      }

      .logo-wrapper {
        position: relative;
        z-index: 2;
        text-align: center;
        padding: 50px;
        max-width: 500px;

        .logo-animation {
          position: relative;
          margin-bottom: 30px;

          .main-logo {
            width: 200px;
            height: 200px;
            margin: 0 auto;
            border-radius: 50%;
            border: 3px solid rgba(255, 255, 255, 0.3);
            box-shadow: 0 0 50px rgba(64, 158, 255, 0.5);
            animation: pulse 3s infinite;
            background: rgba(255, 255, 255, 0.1);
            padding: 15px;
          }
        }

        .logo-title {
          color: #fff;
          font-size: 52px;
          font-weight: 800;
          letter-spacing: 3px;
          margin: 0 0 20px 0;
          text-transform: uppercase;
          text-shadow: 0 0 30px rgba(64, 158, 255, 0.7);
          background: linear-gradient(90deg, #fff, #409eff);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }

        .logo-subtitle {
          color: rgba(255, 255, 255, 0.9);
          font-size: 22px;
          margin: 0 0 30px 0;
          font-weight: 300;
        }

        .logo-description {
          color: rgba(255, 255, 255, 0.8);
          font-size: 18px;
          font-weight: 300;
          letter-spacing: 1px;
        }
      }
    }

    .login-section {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(15, 20, 40, 0.85);

      .login-box {
        width: 100%;
        max-width: 450px;
        padding: 50px 40px;

        .login-header {
          margin-bottom: 40px;
          text-align: center;

          h2 {
            color: #fff;
            font-size: 32px;
            margin: 0 0 12px 0;
            font-weight: 700;
            letter-spacing: 1px;
          }

          p {
            color: rgba(255, 255, 255, 0.7);
            margin: 0;
            font-size: 18px;
            font-weight: 300;
          }
        }

        .login-form {
          .custom-input {
            :deep(.el-input__wrapper) {
              background: rgba(255, 255, 255, 0.1);
              border: 1px solid rgba(255, 255, 255, 0.25);
              border-radius: 12px;
              box-shadow: none;
              margin-bottom: 25px;
              height: 56px;

              &:hover {
                border-color: rgba(100, 170, 255, 0.7);
              }

              &.is-focus {
                border-color: #409eff;
                box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
              }
            }

            :deep(.el-input__inner) {
              background: transparent;
              color: #fff;
              font-size: 16px;
              height: 56px;

              &::placeholder {
                color: rgba(255, 255, 255, 0.6);
              }
            }

            :deep(.input-icon) {
              color: rgba(255, 255, 255, 0.8);
              font-size: 18px;
            }
          }

          .captcha-container {
            display: flex;
            align-items: center;
            gap: 15px;

            .captcha-input {
              flex: 1;
              margin-bottom: 0;
            }

            .login-code {
              height: 56px;
              flex-shrink: 0;

              img {
                cursor: pointer;
                vertical-align: middle;
                border-radius: 10px;
                border: 1px solid rgba(255, 255, 255, 0.25);
                height: 56px;
                box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
                transition: all 0.3s ease;

                &:hover {
                  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
                  transform: scale(1.02);
                }
              }
            }
          }

          .login-options {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;

            :deep(.el-checkbox) {
              color: rgba(255, 255, 255, 0.8);
              font-size: 15px;

              .el-checkbox__input.is-checked + .el-checkbox__label {
                color: #409eff;
              }

              .el-checkbox__inner {
                background: rgba(255, 255, 255, 0.1);
                border-color: rgba(255, 255, 255, 0.3);
                width: 18px;
                height: 18px;
              }

              .el-checkbox__inner::after {
                border-color: #409eff;
                width: 4px;
                height: 8px;
                left: 6px;
                top: 2px;
              }
            }

            .register-link {
              color: #409eff;
              text-decoration: none;
              font-size: 15px;

              &:hover {
                text-decoration: underline;
              }
            }
          }

          .login-button {
            background: linear-gradient(90deg, #409eff, #1a6bed);
            border: none;
            border-radius: 12px;
            height: 56px;
            font-size: 18px;
            font-weight: 600;
            letter-spacing: 2px;
            text-transform: uppercase;
            margin-bottom: 30px;
            box-shadow: 0 10px 20px rgba(64, 158, 255, 0.3);
            transition: all 0.3s ease;

            &:hover {
              background: linear-gradient(90deg, #1a6bed, #409eff);
              box-shadow: 0 15px 30px rgba(64, 158, 255, 0.5);
              transform: translateY(-2px);
            }
          }

          .divider {
            display: flex;
            align-items: center;
            text-align: center;
            color: rgba(255, 255, 255, 0.6);
            font-size: 15px;
            margin: 35px 0;

            &::before,
            &::after {
              content: '';
              flex: 1;
              border-bottom: 1px solid rgba(255, 255, 255, 0.15);
            }

            &::before {
              margin-right: 15px;
            }

            &::after {
              margin-left: 15px;
            }
          }

          .social-login {
            display: flex;
            justify-content: center;
            gap: 20px;

            :deep(.el-button) {
              background: rgba(255, 255, 255, 0.1);
              border: 1px solid rgba(255, 255, 255, 0.25);
              color: #fff;
              width: 56px;
              height: 56px;
              padding: 15px;
              font-size: 20px;
              transition: all 0.3s ease;

              &:hover {
                background: rgba(64, 158, 255, 0.3);
                border-color: #409eff;
                transform: translateY(-5px);
                box-shadow: 0 10px 20px rgba(64, 158, 255, 0.3);
              }
            }
          }
        }
      }
    }
  }

  .el-login-footer {
    height: 50px;
    line-height: 50px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: rgba(255, 255, 255, 0.7);
    font-family: 'Helvetica Neue', Arial, sans-serif;
    font-size: 14px;
    letter-spacing: 1px;
    z-index: 1;
    background: rgba(0, 0, 0, 0.3);
    backdrop-filter: blur(5px);
  }
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.6);
  }
  70% {
    box-shadow: 0 0 0 20px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

// 响应式设计
@media (max-width: 992px) {
  .login-container {
    flex-direction: column;
    height: auto;
    min-height: auto;

    .logo-section {
      padding: 50px 30px;

      .logo-wrapper {
        .logo-animation {
          .main-logo {
            width: 150px;
            height: 150px;
          }
        }

        .logo-title {
          font-size: 42px;
        }

        .logo-subtitle {
          font-size: 18px;
        }
      }
    }

    .login-section {
      padding: 50px 30px;
    }
  }
}

@media (max-width: 768px) {
  .login-container {
    margin: 20px;
    max-height: none;

    .login-box {
      padding: 30px 20px !important;
    }
  }
}
</style>
